package com.mzwise.tunnel.service;
import com.github.wxpay.sdk.WXPay;
import com.mzwise.tunnel.service.Configs;
import com.mzwise.tunnel.wx.pay.dto.UnifiedTradeRequest;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付相关工具
 */
public class WxPayService {

    public WxPayService(Configs configs) {
        if (configs.getWxPayConfig() != null) {
            try {
                this.wxpay = new WXPay(configs.getWxPayConfig());
                System.out.println("tunnel:微信支付通道开启");
            } catch (Exception e) {
                System.out.println("tunnel:微信支付通道开启错误");
                e.printStackTrace();
            }
        }
    }

    private WXPay wxpay;

    /**
     * 正常金额转微信金额*100
     * @param amount
     * @return
     */
    public String amountToFee(BigDecimal amount) {
        return amount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_UP).toString();
    }

    /**
     * 微信二维码统一支付下单
     * @return
     * @throws Exception
     * @author qsh
     */
    public Map<String, String> unifiedCreate(UnifiedTradeRequest request) throws Exception {
//        WxConfig config = new WxConfig();
//        WXPay wxpay = new WXPay(config);
        InetAddress inetAddress = InetAddress.getLocalHost();
        String ip = inetAddress.getHostAddress().toString();//获得本机Ip
        String spbill_create_ip = ip;
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "Mpay");
        data.put("openid", request.getOpenid());
        data.put("out_trade_no",request.getOutTradeNo());
        data.put("sub_mch_id", request.getSubMchId());//商户号
        //data.put("sub_mch_id", SellerId);//商户号
        data.put("device_info", "WEB");
        data.put("fee_type", "CNY");
        data.put("total_fee", request.getTotalFee());
        data.put("sign_type", "HMAC-SHA256");
        data.put("spbill_create_ip", "" + spbill_create_ip + "");
        data.put("notify_url", request.getUrlBack()); // 回调地址
        data.put("trade_type", "JSAPI");  // 此处指定为扫码支付
        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println("resp=" + resp);
            String packag = "prepay_id=" + resp.get("prepay_id");
            String time_stamp = Long.toString(System.currentTimeMillis());
            Map<String, String> repData = new HashMap<>();
            repData.put("appId", resp.get("appid"));
            repData.put("package", packag);
            repData.put("signType", "HMAC-SHA256");
            repData.put("nonceStr", resp.get("nonce_str"));
            repData.put("timeStamp", time_stamp);
            return repData;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 付款码支付
     * @param outTradeNo
     * @param subMchId
     * @param authCode
     * @param totalFee
     * @return
     * @throws Exception
     */
    public Map<String, String> microPay(String outTradeNo, String subMchId, String authCode, String totalFee) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "Mpay");
        data.put("out_trade_no", outTradeNo);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", totalFee);
        data.put("spbill_create_ip", Inet4Address.getLocalHost().getHostAddress());
        data.put("sub_mch_id", subMchId);
        data.put("auth_code", authCode);
        try {
            Map<String, String> resp = wxpay.microPay(data);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 作用：根据授权码获取openid<br>
     * 场景：扫码支付时验证身份
     * @param authCode 授权码
     * @return API返回数据
     * @throws Exception
     */
    public String authCodeToOpenid(String authCode, String subMchId) {
        try {
            Map<String, String> data = new HashMap<String, String>();
            data.put("sub_mch_id", subMchId);
            data.put("auth_code", authCode);
            Map<String, String> resp = wxpay.authCodeToOpenid(data);
            return resp.get("openid");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return null;
        }
    }

    /**
     * 获取刷脸调用凭证
     * @param subMchId
     * @param rawdata
     * @param device_id
     * @return
     * @throws Exception
     */
    public Map<String, String> getFaceAuthinfo(String subMchId, String rawdata, String device_id) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        data.put("sub_mch_id", subMchId);
        data.put("device_id", device_id);
        data.put("store_id", "1");
        data.put("store_name", "高新一店");
        data.put("rawdata", rawdata);
        data.put("version", "1");
        data.put("now", "" + (System.currentTimeMillis() / 1000));
        try {
            Map<String, String> resp = wxpay.getFaceAuthinfo(data);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 刷脸支付
     * @param outTradeNo
     * @param subMchId
     * @param faceCode
     * @param openid
     * @param totalFee
     * @return
     * @throws Exception
     */
    public Map<String, String> facePay(String outTradeNo, String subMchId, String faceCode, String openid, String totalFee) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "Mpay");
        data.put("out_trade_no", outTradeNo);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", totalFee);
        data.put("spbill_create_ip", Inet4Address.getLocalHost().getHostAddress());
        data.put("sub_mch_id", subMchId);
        data.put("face_code", faceCode);
        data.put("openid", openid);
        try {
            Map<String, String> resp = wxpay.facePay(data);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询订单结果
     * @param outTradeNo
     * @param subMchId
     * @return
     * @throws Exception
     */
    public Map<String, String> orderQuery(String outTradeNo, String subMchId) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        data.put("sub_mch_id", subMchId);
        data.put("out_trade_no", outTradeNo);
        try {
            Map<String, String> resp = wxpay.orderQuery(data);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 微信退款
     * @param out_trade_no
     * @param total_fee
     * @param refund_fee
     * @param subMchId
     * @param out_refund_no
     * @return
     * @throws Exception
     */
    public Map<String, String> refund(String out_trade_no, String total_fee, String refund_fee, String subMchId, String out_refund_no) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        data.put("total_fee", total_fee);
        data.put("refund_fee", refund_fee);
        data.put("sub_mch_id", subMchId);
        data.put("out_trade_no", out_trade_no);
        data.put("out_refund_no", out_refund_no);
        try {
            Map<String, String> resp = wxpay.refund(data);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * XML格式字符串转换为Map
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {

            throw ex;
        }

    }
}
